<?php


namespace App\Http\Controllers\Documents;

use App\Http\Controllers\common\LMReturn;
use App\Http\Resources\TbDocument as Document;
use App\Models\TbDocumentTag;
use App\Http\Controllers\Controller;
use App\Models\TbDocumentImg;
use App\Models\TbDocumentsClassify;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\TbDocument;
use App\Models\Worker;
use Carbon\Carbon;

class DocumentsController extends Controller
{
    // 文章分类管理
    public function DocumentClassfily(Request $request)
    {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $worker_id = $tokenInfo['worker_id'];
        //        $if_power = utils::if_power($worker_id);
        //        if ($if_power == 0) {
        //            return LMReturn::Error('无权操作');
        //        }
        $all = $request->all();
        if (empty($all['type'])) {
            return LMReturn::Error('未传入操作模式');
        }
        if ($all['type'] == 1) {
            if (empty($all['name'])) {
                return LMReturn::Error('未传入分类名称');
            }
            //            if (empty($all['p_id']) && empty($all['h_id'])) {
            //                return LMReturn::Error('缺少传参');
            //            }
            // 增加,需要传入p_id,没传入p_id就是加顶级分类，如果传入h_id就放在h_id后面，否则放在最前面
            DB::beginTransaction();
            try {
                $new_classify = new TbDocumentsClassify();
                $new_classify->name = $all['name'];
                $new_classify->weight = 1;
                $new_classify->save();
                $p_id = null;
                if (isset($all['p_id'])) {
                    $p_classify = TbDocumentsClassify::find($all['p_id']);
                    if ($p_classify) {
                        $p_id = $all['p_id'];
                    }
                }
                $h_id = null;
                if (isset($all['h_id'])) {
                    $h_classify = TbDocumentsClassify::find($all['h_id']);
                    if ($h_classify) {
                        $h_id = $h_classify->id;
                    }
                }
                utils::add_classify($new_classify, $p_id, $h_id);
                DB::commit();
                return LMReturn::Success();
            } catch (\Throwable $th) {
                DB::rollBack();
                return LMReturn::Error('添加失败');
            }
        } elseif ($all['type'] == 2) {
            // 删除
            if (empty($all['classify_id'])) {
                return LMReturn::Error('未传入分类id');
            }
            return utils::del_classify($all['classify_id']);
        } elseif ($all['type'] == 3) {
            // 修改
            if (empty($all['up_id'])) {
                return LMReturn::Error('未传入待修改分类id');
            }
            if (isset($all['name'])) {
                $name = $all['name'];
                $up_classify = TbDocumentsClassify::find($all['up_id']);
                if ($up_classify) {
                    $up_classify->name = $name;
                    $up_classify->save();
                } else {
                    return LMReturn::Error('未找到该分类');
                }
                if (isset($all['refer_id'])) {
                    if ($all['refer_id'] == $all['up_id']) {
                        return LMReturn::Error('不能将自己做为参照');
                    }
                    if (isset($all['up_type']) && $all['up_type'] == 3) {
                        if ($all['refer_id'] == $up_classify->p_id) {
                            return LMReturn::Success();
                        }
                    }
                }
            }
            if (empty($all['refer_id'])) {
                return LMReturn::Error('未传入参照分类id');
            }
            if (empty($all['up_type'])) {
                return LMReturn::Error('未传入修改方式');
            }
            return utils::update_classify($all['up_id'], $all['refer_id'], $all['up_type']);
        } elseif ($all['type'] == 4) {
            if (isset($all['classify_id'])) {
                // 查询
                return LMReturn::Success(utils::sele_classify($all['classify_id']));
            } else {
                return LMReturn::Success(utils::sele_classify());
            }
        } else {
            return LMReturn::Error('传入操作模式不存在');
        }
    }

    // 文章管理
    public function DocumentsManage(Request $request)
    {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $worker_id = $tokenInfo['worker_id'];
        //        $if_power = utils::if_power($worker_id);
        //        if ($if_power == 0) {
        //            return LMReturn::Error('无权操作');
        //        }
        $worker = Worker::find($worker_id);
        $all = $request->all();
        if (empty($all['type'])) {
            return LMReturn::Error('未传入操作模式');
        }
        if ($all['type'] == 1) {
            // 增
            if (empty($all['title'])) {
                return LMReturn::Error('未传入文章标题');
            }
            if (empty($all['docs'])) {
                return LMReturn::Error('未传入文章内容');
            }
            if (empty($all['classify_id'])) {
                return LMReturn::Error('未传入文章类型');
            } else {
                $clsaaify = TbDocumentsClassify::find($all['classify_id']);
                if (empty($clsaaify)) {
                    return LMReturn::Error('没有该文章类型');
                }
            }
            if (empty($all['introduction'])) {
                $introduction = null;
            } else {
                $introduction = $all['introduction'];
            }
            if (empty($all['img_id'])) {
                $thumbnail = null;
                $document_img = null;
            } else {
                $img_id = $all['img_id'];
                $document_img = TbDocumentImg::find($img_id);
                if ($document_img) {
                    $thumbnail = $document_img->img_url;
                } else {
                    $thumbnail = null;
                }
            }
            $new_document = new TbDocument();
            $new_document->title = $all['title'];
            $new_document->create_date = date(Carbon::now());
            $new_document->introduction = $introduction;
            $new_document->thumbnail = $thumbnail;
            $head = '<!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
                <title>内容</title>
            </head>
            <body>';
            $footer = '</body>
            </html>';
            $new_document->docs = $head . $all['docs'] . $footer;
            $new_document->author = $worker->name;
            $new_document->views = 0;
            $new_document->documents_classify_id = $all['classify_id'];
            $new_document->worker_id = $worker_id;
            $new_document->save();
            if ($document_img) {
                $document_img->document_id = $new_document->id;
                $document_img->save();
            }
            if (isset($all['tag_type_list'])) {
                $tag_types = [];
                foreach ($all['tag_type_list'] as $tag_type) {
                    $tag_types[] = new TbDocumentTag(['tag_type' => $tag_type]);
                }
                $new_document->tb_document_tags()->saveMany($tag_types);
            }
            return LMReturn::Success();
        } elseif ($all['type'] == 2) {
            // 删
            if (empty($all['document_id'])) {
                return LMReturn::Error('未传入文章id');
            } else {
                $document = TbDocument::find($all['document_id']);
                if (!$document) {
                    return LMReturn::Error('未找到该文章');
                }
                //                if ($document) {
                //                    $role = WorkerRole::where('worker_id', $worker_id)->where('role_id', 1)->first();
                //                    if (empty($role) && $worker_id != $document->worker_id) {
                //                        return LMReturn::Error('非超级管理员只能删除自己的文章');
                //                    }
                //                } else {
                //                    return LMReturn::Error('未找到该文章');
                //                }
            }
            $document_imgs = TbDocumentImg::where('document_id', $all['document_id'])->get();
            if ($document_imgs) {
                foreach ($document_imgs as $document_img) {
                    utils::del_img($document_img['img_path']);
                }
                TbDocumentImg::where('document_id', $all['document_id'])->delete();
            }
            TbDocumentTag::where('document_id', $all['document_id'])->delete();
            $document->delete();
            return LMReturn::Success();
        } elseif ($all['type'] == 3) {
            // 改
            DB::beginTransaction();
            try {
                if (empty($all['document_id'])) {
                    return LMReturn::Error('未传入文章id');
                } else {
                    $document = TbDocument::find($all['document_id']);
                    if (empty($document)) {
                        return LMReturn::Error('未找到文章id');
                    }
                    //                    } else {
                    //                        $role = WorkerRole::where('worker_id', $worker_id)->where('role_id', 1)->first();
                    //                        if (empty($role) && $worker_id != $document->worker_id) {
                    //                            return LMReturn::Error('非超级管理员只能修改自己的文章');
                    //                        }
                    //                    }
                }
                if (isset($all['tag_type_list'])) {
                    TbDocumentTag::where('document_id', $all['document_id'])->delete();
                    $tag_types = [];
                    foreach ($all['tag_type_list'] as $tag_type) {
                        $tag_types[] = new TbDocumentTag(['tag_type' => $tag_type]);
                    }
                    $document->tb_document_tags()->saveMany($tag_types);
                } else {
                    TbDocumentTag::where('document_id', $all['document_id'])->delete();
                }
                if (isset($all['title'])) {
                    $document->title = $all['title'];
                }
                if (isset($all['introduction'])) {
                    $document->introduction = $all['introduction'];
                }
                if (isset($all['img_id'])) {
                    $document_imgs = TbDocumentImg::where('document_id', $all['document_id'])->where('img_type', 1)->get();
                    foreach ($document_imgs as $document_img) {
                        if ($document_img['id'] != $all['img_id']) {
                            utils::del_img($document_img['img_path']);
                            TbDocumentImg::find($document_img['id'])->delete();
                        }
                    }
                    $new_img = TbDocumentImg::find($all['img_id']);
                    $new_img->document_id = $all['document_id'];
                    $new_img->save();
                    $document->thumbnail = $new_img->img_url;
                    $document->save();
                }
                if (isset($all['docs'])) {
                    $head = '<!DOCTYPE html>
                    <html lang="en">
                    <head>
                        <meta charset="UTF-8">
                        <meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
                        <title>内容</title>
                    </head>
                    <body>';
                    $footer = '</body>
                    </html>';
                    $document->docs = $head . $all['docs'] . $footer;
                }
                if (isset($all['classify_id'])) {
                    $document->documents_classify_id = $all['classify_id'];
                }
                $document->save();
                DB::commit();
                return LMReturn::Success();
            } catch (\Throwable $th) {
                DB::rollBack();
                return LMReturn::Error('修改失败');
            }
        } elseif ($all['type'] == 4) {
            // 查
            if (isset($all['classify_id'])) {
                $classify = TbDocumentsClassify::find($all['classify_id']);
                if ($classify) {
                    $classify_list = utils::get_child_list($all['classify_id']);
                    $classify_list[] = $all['classify_id'];
                    $documents = TbDocument::whereIn('documents_classify_id', $classify_list)
                        ->with('tb_documents_classify')
                        ->with('tb_document_tags')
                        ->orderBy('tb_documents.create_date', 'desc')
                        ->get();
                    $document_list = [];
                    foreach ($documents as $document) {
                        $document_dic['id'] = $document->id;
                        $document_dic['title'] = $document->title;
                        $document_dic['create_date'] = date($document->create_date);
                        $document_dic['introduction'] = $document->introduction;
                        $document_dic['img_url'] = $document->thumbnail;
                        $document_dic['author'] = $document->author;
                        $document_dic['views'] = $document->views;
                        $document_dic['classify'] = $document->tb_documents_classify->name;
                        $document_dic['classify_id'] = $document->documents_classify_id;
                        $document_dic['worker_id'] = $document->worker_id;
                        $document_tags = $document->tb_document_tags;
                        $document_tag_list = [];
                        if (count($document_tags) > 0) {
                            foreach ($document_tags as $document_tag) {
                                $document_tag_list[] = $document_tag['tag_type'];
                            }
                        }
                        $document_dic['document_tags'] = $document_tag_list;
                        $document_list[] = $document_dic;
                    }
                    $size = $all['size'] ?? 15;
                    $page = $all['page'] ?? 1;
                    $start = ($page - 1) * $size;
                    $article = array_slice($document_list, $start, $size);
                    $datas_list = [];
                    $count = count($document_list);
                    $datas_list['total'] = $count;
                    $datas_list['data'] = $article;
                    return LMReturn::Success($datas_list);
                } else {
                    return LMReturn::Error('没有该文章类型');
                }
            } elseif (isset($all['document_id'])) {
                $document = TbDocument::where('id', $all['document_id'])->with('tb_documents_classify')->with('tb_document_imgs')->with('tb_document_tags')->first();
                if ($document) {
                    $views = $document->views + 1;
                    $document->views = $views;
                    $document->save();
                    $document_dic['id'] = $document->id;
                    $document_dic['title'] = $document->title;
                    $document_dic['create_date'] = $document->create_date;
                    $document_dic['introduction'] = $document->introduction;
                    $document_dic['img_url'] = $document->thumbnail;
                    $document_dic['author'] = $document->author;
                    $document_dic['views'] = $views;
                    $document_dic['doce'] = $document->docs;
                    $document_dic['classify_id'] = $document['tb_documents_classify']['id'];
                    $document_dic['classify'] = $document['tb_documents_classify']['name'];
                    $document_dic['worker_id'] = $document->worker_id;
                    $document_dic['tb_document_imgs'] = $document['tb_document_imgs'][0] ?? null;
                    $document_tags = $document->tb_document_tags;
                    $document_tag_list = [];
                    if (count($document_tags) > 0) {
                        foreach ($document_tags as $document_tag) {
                            $document_tag_list[] = $document_tag['tag_type'];
                        }
                    }
                    $document_dic['document_tags'] = $document_tag_list;
                    return LMReturn::Success($document_dic);
                } else {
                    return LMReturn::Error('未找到该文章');
                }
            } else {
                return LMReturn::Error('传参错误');
            }
        }
        return LMReturn::Success([], '此传参有漏洞，请了；联系管理员');
    }

    // 上传图片接口
    public function UploadImage(Request $request)
    {
        // 接参
        try {
            //去验证token值
            $tokenInfo = json_decode($this->verifyTokenLm(), true);
            //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
            if ($tokenInfo['code'] == 400) {
                return LMReturn::tokenErr($tokenInfo['msg'], $tokenInfo['code']);
            }
            $all = $request->all();
            if (empty($all['img_type'])) {
                return LMReturn::Error('未传入图片类型');
            }
            if (isset($all['img_id'])) {
                $image = TbDocumentImg::find($all['img_id']);
                if ($image) {
                    $sta = utils::del_img($image->img_path);
                    if ($sta == 1) {
                        $image->delete();
                    }
                } else {
                    return LMReturn::Error('未找到该图片');
                }
            }
            $file = $all['file'] ?? false;
            if (!$file) {
                return LMReturn::Error("请上传图片", 'IC007');
            }
            // 获取上传文件的后缀
            $ext = $file->getClientOriginalExtension();
            $filename = md5(uniqid()) . "." . $ext;
            $realPath = $file->getRealPath();
            $path = 'image_hx/' . date("Ymd") . '/' . $filename; // 路径
            $exists = Storage::disk('new_ftp')->put('htdocs/' . $path, file_get_contents($realPath));
            if ($exists) {
                $url = env("FTP2_URL") . $path;
            } else {
                return LMReturn::Error('图片上传错误', 'IC005');
            }
            $document = new TbDocumentImg();
            $document->img_path = $path;
            $document->img_url = $url;
            $document->img_type = (int)$all['img_type'];
            $document->save();
            $data['img_id'] = $document->id;
            $data['img_url'] = $url;
            return LMReturn::Success($data);
        } catch (\Throwable $th) {
            return LMReturn::Error("参数错误", 'IC006');
        }
    }

    // 删除图片接口
    public function DeleteImage(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::tokenErr($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        if (empty($all['img_id'])) {
            return LMReturn::Error('未传入图片id');
        }
        $image = TbDocumentImg::find($all['img_id']);
        if ($image) {
            $sta = utils::del_img($image->img_path);
            if ($sta == 1) {
                $image->delete();
                return LMReturn::Success();
            } else {
                return LMReturn::Error('删除失败');
            }
        } else {
            return LMReturn::Error('未找到该图片');
        }
    }

    // App端文章类型查询
    public function AppSelectDocumentClassify(Request $request)
    {
        $tree_list = utils::sele_classify(1);
        $list['class_list'] = $tree_list['tree_list'];
        return LMReturn::Success($list);
    }

    // App端文章内容查询
    public function AppSelectDocument(Request $request)
    {
        $all = $request->all();
        if (isset($all['classify_id'])) {
            $classify = TbDocumentsClassify::find($all['classify_id']);
            if ($classify) {
                $classify_list = utils::get_child_list($all['classify_id']);
                $classify_list[] = $all['classify_id'];
                $documents = TbDocument::whereIn('documents_classify_id', $classify_list)
                    ->select(
                        'tb_documents.id',
                        'tb_documents.title',
                        'tb_documents.create_date',
                        'tb_documents.introduction',
                        'tb_documents.thumbnail',
                        'tb_documents.author',
                        'tb_documents.views',
                        'tb_documents.worker_id',
                        'tb_documents.documents_classify_id',
                        'tb_documents_classify.name'
                    )
                    ->Join('tb_documents_classify', 'tb_documents_classify.id', '=', 'tb_documents.documents_classify_id')
                    ->orderBy('tb_documents.create_date', 'desc')
                    ->get();
                $document_list = [];
                foreach ($documents as $document) {
                    $document_dic['id'] = $document->id;
                    $document_dic['title'] = $document->title;
                    $document_dic['create_date'] = date('Y-m-d', strtotime($document->create_date));
                    $document_dic['introduction'] = $document->introduction;
                    $document_dic['img_url'] = $document->thumbnail;
                    $document_dic['author'] = $document->author;
                    $document_dic['views'] = $document->views;
                    $document_dic['classify'] = $document->name;
                    $document_dic['classify_id'] = $document->documents_classify_id;
                    $document_dic['worker_id'] = $document->worker_id;
                    $document_list[] = $document_dic;
                }
                $size = $all['size'] ?? 15;
                $page = $all['page'] ?? 1;
                return LMReturn::Success(utils::Paging($document_list, $page, $size));
            } else {
                return LMReturn::Error('没有该文章类型');
            }
        } elseif (isset($all['document_id'])) {
            $document = TbDocument::where('id', $all['document_id'])->with('tb_documents_classify')->with('tb_document_imgs')->first();
            if ($document) {
                $views = $document->views + 1;
                $document->views = $views;
                $document->save();
                $document_dic['id'] = $document->id;
                $document_dic['title'] = $document->title;
                $document_dic['create_date'] = $document->create_date;
                $document_dic['introduction'] = $document->introduction;
                $document_dic['img_url'] = $document->thumbnail;
                $document_dic['author'] = $document->author;
                $document_dic['views'] = $views;
                $document_dic['doce'] = $document->docs;
                $document_dic['classify'] = $document['tb_documents_classify']['name'];
                $document_dic['worker_id'] = $document->worker_id;
                $document_dic['tb_document_imgs'] = $document['tb_document_imgs'][0] ?? null;
                return LMReturn::Success($document_dic);
            } else {
                return LMReturn::Error('未找到该文章');
            }
        } elseif (isset($all['tag_type'])) {
            $tag = $all['tag_type'];
            $documents = TbDocument::whereHas('tb_document_tags', function ($query) use ($tag) {
                $query->where('tag_type', $tag);
            })
            ->orderBy('tb_documents.create_date', 'desc')
            ->get();
            if ($documents) {
                $document_list = [];
                foreach ($documents as $document) {
                    $document_dic['id'] = $document->id;
                    $document_dic['title'] = $document->title;
                    $document_dic['create_date'] = date($document->create_date);
                    $document_dic['introduction'] = $document->introduction;
                    $document_dic['img_url'] = $document->thumbnail;
                    $document_dic['author'] = $document->author;
                    $document_dic['views'] = $document->views;
                    $document_dic['classify'] = $document->name;
                    $document_dic['classify_id'] = $document->documents_classify_id;
                    $document_dic['worker_id'] = $document->worker_id;
                    $document_list[] = $document_dic;
                }
                $size = $all['size'] ?? 15;
                $page = $all['page'] ?? 1;
                return LMReturn::Success(utils::Paging($document_list, $page, $size));
            } else {
                return LMReturn::Success();
            }
        } else {
            return LMReturn::Error('传参错误');
        }
    }

    // App端活动中心文章查询
    public function AppActiveDocument(Request $request)
    {
        $all = $request->all();
        if (!isset($all['document_type'])) {
            return LMReturn::Error('未传入需要查找的标签');
        }
        $size = $all['size'] ?? 10;
        $document_type = $all['document_type'];
        $documents = TbDocument::where('documents_classify_id', 3)
        ->whereHas('tb_document_tags', function ($query) use ($document_type) {
            $query->where('tag_type', $document_type);
        })
        ->with('tb_document_tags')
        ->with('tb_document_imgs')
        ->orderBy('tb_documents.create_date', 'desc')
        ->paginate($size);
        if ($documents) {
            $documents = Document::collection($documents);
            return LMReturn::Success($documents);
        } else {
            return LMReturn::Success();
        }
    }
}
